package middlewares

import (
	"os"

	"github.com/Qsnh/goa/models"
	"github.com/Qsnh/goa/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

var LoginCheckFilter = func(ctx *context.Context) {
	logs.Debug("LoginCheckFilter")
	url := os.Getenv("LOGIN_URL")
	logs.Debug(url)
	session := ctx.GetCookie("session")
	if len(session) == 0 { // session 为空
		ctx.Redirect(302, url)
	}
	fs, err := utils.DecodeFlaskSession(session)
	if err == nil {
		// session 正确，查看是否登陆，这里简化处理，存在userid即认为登陆，否则跳转登陆页
		user := models.User{}
		if err := orm.NewOrm().QueryTable("user").Filter("userid", fs.UserID).One(&user); err != nil {
			ctx.Redirect(302, url) // beego.URLFor("UserController.Login")
			return
		}
	} else { // session非法
		ctx.Redirect(302, url)
		logs.Error(err)
	}
	//ctx.Redirect(302, beego.URLFor("UserController.Login"))
	return

}

func LoginCheck() {
	beego.InsertFilter("/member/*", beego.BeforeRouter, LoginCheckFilter)
}
